package model

import (
	"encoding/json"
	"github.com/gorilla/websocket"
	"io/ioutil"
	"strings"
	"time"
)

var (
	Mac          map[string]map[string]interface{}     //设备保存列表
	MacInfoCache map[string]interface{}                //设备信息缓存
	CleanSleep   time.Duration                     = 1 //定时清空 失效的设备 间隔时间
	IntranetIp   string                                //本身内网IP
)

type MacInfo struct {
	GOOS        string //平台
	GOARCH      string //位数
	HOSTNAME    string //计算器名称
	PUBLICIP    string //公网IP
	PUBLICERR   string //公网获取错误信息
	CPUNUM      int
	STIME       time.Time
	TESTSPEED   string //网速测试
	OffOlineLog map[string]map[string]map[string]string
	TYPE        uint //0 正常macinfo 1 清空日志
}

func init() {
	Mac = make(map[string]map[string]interface{})
	MacInfoCache = make(map[string]interface{})
	IntranetIp = GetIntranetIp()
}

//定时清空 失效的设备
func ClientOverTime() {
	ticker := time.NewTicker(time.Second * CleanSleep)
	for _ = range ticker.C {
		if len(Mac) > 0 {
			wg.Lock()
			for k, v := range Mac {
				if time.Now().Unix() > v["overtime"].(int64) {
					Mac[k]["OffOnline"] = 1

					//delete(Mac, k)
				}
			}
			wg.Unlock()

			if wbsCon != nil {
				wg.Lock()
				if b, err := json.Marshal(Mac); err == nil {
					if err := wbsCon.WriteMessage(websocket.TextMessage, b); err != nil {
						Log.Println("websocket WriteMessage Err:", err)
					}
				}
				wg.Unlock()
			}
		}

	}
}

//定时cache
func ClientCache() {
	ticker := time.NewTicker(time.Second * 10)
	for _ = range ticker.C {
		if len(Mac) > 0 {
			wg.Lock()
			jsonStr, err := json.Marshal(Mac)
			wg.Unlock()
			if err != nil {
				Log.Println("MapToJson err: ", err)
			}
			if ioutil.WriteFile("./Mac.cache", jsonStr, 0644) != nil {
				Log.Println("写入文件失败", err)
			}
		}
	}
}

//定时记录失败的设备
func ClientFailNumLog() {
	ticker := time.NewTicker(time.Second * 60)
	for _ = range ticker.C {
		if len(Mac) > 0 {
			wg.Lock()
			for k, v := range Mac {
				if time.Now().Unix() > v["overtime"].(int64) {
					Mac[k]["FailNum"] = Mac[k]["FailNum"].(int64) + 1
					//FailNum := strconv.Itoa(int(Mac[k]["FailNum"].(int64)))
					//时间，本机IP，远程IP，失败次数
					//content := strings.Join([]string{"|", IntranetIp, "|", Mac[k]["ip"].(string), "|", FailNum}, "")
					content := strings.Join([]string{"|", Mac[k]["ip"].(string)}, "")
					OfflineLog.Println(content)
				}
			}
			wg.Unlock()
		}
	}
}
